import api from '../../../fetch/api'
import Chimee from 'chimee';
import hls from 'chimee-kernel-hls';
export default {
  data() {
    return {
      bigImgPath: '',
      existScanImg: false,
      destroy: false,
    }
  },
  created() {
    // setInterval(this.scanImg(),5000);
    // this.getItemList();
    this.videoHeatbeat();
    this.destroy = false;
    this.initWebsocket();


  },
  mounted() {
    // let _this = this;
    // setInterval(function () {
    //   _this.palyMp3();
    // }, 5000)
  },
  watch: {
    alarmReconect: function (val) {
      let _this = this;
      console.log("执行了alarmReconect", _this.alarmReconectNumber)
      _this.alarmReconectNumber = _this.alarmReconectNumber + 1;
      // 20秒钟重连一次，超过十次取消重连，提示信息
      if (_this.alarmReconectNumber >= 10) {
        _this.showToast("提醒模块失去连接，请联系管理员", 2, 3000);
      } else {
        setTimeout(function () {
          _this.initWebsocket();
        }, 20000)
      }
    },
    alarmSwitch: function (val) {
      console.log("alarmSwitch", val)
      this.toOpenModal('alarmModal');
    }
  },

  beforeDestroy() {
    this.destroy = true;
    this.channelList.forEach(element => {
      if (element.chimee) {
        element.chimee.destroy();
      }
    });
    console.log("monitor beforeDestroy");
  },
  filters: {
    strFilter(val, length) {
      let str = val;
      if (str.length > length) {
        return str.substring(0, length) + "...";
      }
      return str;
    },
    nameFilter(park, path) {
      let str = park + "-" + path;
      if (str.length > 18) {
        return str.substring(0, 18) + "...";
      }
      return str;
    },
    controlTypeShow: function (value) {
      if (value == 1) {
        return "开闸";
      } else {
        return "关闸";
      }
    },
    operateStatusShow: function (value) {
      if (value == 1) {
        return "成功";
      } else {
        return "失败";
      }
    }
  },
  methods: {
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getItemList(params);
    },
    showBigImgModal(name, path) {
      this.bigImgPath = path;
      this.toOpenImgModal(name, path);
    },
    palyMp3() {
      var x = document.getElementById("myAudio");
      x.play();
    },
    initWebsocket() {
      let _this = this;
      let wsUri;
      if (window.location.protocol.indexOf('https') != -1) {
        wsUri = "wss://" + window.location.host + "/mgr/websocket/emergency.do";
      } else {
        wsUri = "ws://" + window.location.host + "/mgr/websocket/emergency.do";
      }
      console.log('wsUri', wsUri);
      let Socket = new WebSocket(wsUri);
      Socket.onopen = function (evt) {
        console.log("onopen");
        _this.alarmReconectNumber = 0;

        let params = {
        };
        params = $.extend({}, params);
        api.fetchGet('/park/emergency/getUserId.do', params)
          .then(res => {
            let id = res.data.userId;
            var data = {
              userId: id
            };
            Socket.send(JSON.stringify(data));
            console.log("send userId");


          }, err => { });
      };
      Socket.onclose = function (evt) {
        console.log("onclose");
        _this.alarmReconect = Math.random();
      };
      Socket.onmessage = function (evt) {
        console.log("onmessage");
        // setInterval(function () {
        //   Socket.send("hi");
        // }, 6000);
        let data = JSON.parse(evt.data);
        _this.palyMp3();
        _this.alarmData = data;
        _this.alarmSwitch = Math.random();
      };
      Socket.onerror = function (evt) {
        console.log("onerror");
        _this.alarmReconect = Math.random();
      };
    },
    //切换树的状态
    toggleTreeBox() {
      let _this = this;
      _this.isTree == "hide" ? _this.isTree = "show" : _this.isTree = "hide";
    },
    //获取列表
    getItemList(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: 6
        };
      params = $.extend({}, params, aparams);
      // API.coupon.GetTraderListData(params)
      api.fetchGet('/monitor/pageChannel.do', params)
        .then(res => {
          //console.log('getListResult', res)
          let data = res.data,
            list = data.rows;
          self.channelList = list;
          self.total = data.total;
          if (!this.existScanImg) {
            this.existScanImg = true;
            self.scanImg();
          }
        }, err => { })
    },
    scanImg() {
      if (this.destroy) {
        return false;
      }
      // console.log("scan img")
      var self = this;
      var fetchSize = 0;
      var channelImgSize = 0;
      for (var i = 0; i < self.channelList.length; i++) {
        var channel = self.channelList[i];
        if (channel.videoNum == 'x') {
          channelImgSize++;
        }
      }
      if (channelImgSize == 0) {
        setTimeout(function () {
          self.scanImg();
        }, 5000);
      }
      for (let i = 0; i < self.channelList.length; i++) {

        let channel = self.channelList[i];
        // console.log("before:" + channel.id + "==" + i)
        var pictureTime = null;
        if (channel.channelStatus) {
          pictureTime = channel.channelStatus.pictureTime;
        }
        if (channel.videoNum == 'x') {
          var params = {
            channelId: channel.id,
            lastPictureTime: pictureTime
          };
          $.ajax({
            type: 'get',
            url: '/mgr/monitor/getChannelStatus.do',
            data: params,
            cache: false,
            dataType: 'json',
            async: true,
            success: function (res) {
              if (res.status == 1) {
                if (res.data.picture) {
                  res.data.picture = 'data:image/jpg;base64,' + res.data.picture;
                  self.$set(self.channelList[i], 'channelStatus', res.data);
                }
              }
            },
            complete(xhr, ts) {
              fetchSize++;
              if (fetchSize == channelImgSize) {
                setTimeout(function () {
                  self.scanImg();
                }, 5000);
              }
            }
          });
        }
      }
    },
    openGate(channelId) {
      var self = this;
      var params = {
        channelId: channelId
      };
      self.showDialog("确定操作开闸吗?", '', function () {
        api.fetchPost('/monitor/openGate.do', params).then(res => {
          if (res.status == 1) {
            // icon: 0:普通提示 1：正确的提示 2： 错误提示
            // time: 不填默认1000ms
            self.showToast(res.message, 1, 2000);
          } else {
            self.showToast(res.message, 2, 2000)
            return;
          }
        }, err => { })

      })
    },
    closeGate(channelId) {
      var self = this;
      var params = {
        channelId: channelId
      };
      self.showDialog("确定操作关闸吗?", '', function () {
        api.fetchPost('/monitor/closeGate.do', params)
          .then(res => {
            if (res.status == 1) {
              // icon: 0:普通提示 1：正确的提示 2： 错误提示
              // time: 不填默认1000ms
              self.showToast(res.message, 1, 2000);
            } else {
              self.showToast(res.message, 2, 2000)
              return;
            }
          }, err => { })

      })
    },
    photo(channel) {
      var self = this;

      var videoNum = channel.videoNum;
      if (videoNum == "x") {
        videoNum = 1;
      } else {
        videoNum = parseInt(videoNum);
      }
      var camera = channel.cameraList[videoNum - 1];
      var params = {
        channelId: channel.id,
        cameraIp: camera.equipmentRecognitionCameraIp
      };
      self.showDialog("确定摄像头拍照吗?", '', function () {
        api.fetchPost('/monitor/photo.do', params)
          .then(res => {
            if (res.status == 1) {
              // icon: 0:普通提示 1：正确的提示 2： 错误提示
              // time: 不填默认1000ms
              self.showToast(res.message, 1, 2000);
              var params = {
                channelId: channel.id
              };
              setTimeout(function () {
                $.ajax({
                  type: 'get',
                  url: '/mgr/monitor/getChannelStatus.do',
                  data: params,
                  cache: false,
                  dataType: 'json',
                  async: true,
                  success: function (res) {
                    if (res.status == 1) {
                      if (res.data.picture) {
                        res.data.picture = 'data:image/jpg;base64,' + res.data.picture;
                        self.$set(channel, 'channelStatus', res.data);
                      }
                    }
                  }
                });
              }, 1000);


            } else {
              self.showToast(res.message, 2, 2000)
              return;
            }
          }, err => { })

      })
    },
    openGateLog() {
      //按钮详情弹框
      let self = this;
      var params = {
        page: this.switchModalData.pageNumber,
        rp: this.switchModalData.pageSize
      };
      api.fetchGet('/monitor/pageGatewayOperateLog.do', params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.switchModalData.tbodysInfo = list;
          self.switchModalData.total = data.total;
          self.toOpenModal('switchModal');
        }, err => { })
    },
    photoLog() {
      //按钮详情弹框
      let self = this;
      var params = {
        page: this.picModalData.pageNumber,
        rp: this.picModalData.pageSize
      };
      api.fetchGet('/monitor/pageCameraOperateLog.do', params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.picModalData.tbodysInfo = list;
          self.picModalData.total = data.total;
          self.toOpenModal('picModal');
        }, err => { })
    },
    getPicPagination(curPage, pageSize) {
      this.picModalData.pageNumber = curPage;
      this.picModalData.pageSize = pageSize ? pageSize : this.picModalData.pageSize;
      this.photoLog();
    },
    getSwitchPagination(curPage, pageSize) {
      this.switchModalData.pageNumber = curPage;
      this.switchModalData.pageSize = pageSize ? pageSize : this.switchModalData.pageSize;
      this.openGateLog();
    },
    chooseCamera(channelIndex, parkId, cameraSeq) {
      var self = this;
      var params = {
        cameraSeq: cameraSeq,
        parkId: parkId
      };
      self.$set(self.channelList[channelIndex], 'showVideo', true);

      self.$set(self.channelList[channelIndex], 'playerLoading', true);

      $.ajax({
        type: 'get',
        url: '/mgr/monitor/getVideoUrl.do',
        data: params,
        cache: false,
        dataType: 'json',
        async: true,
        success: function (res) {
          if (res.status == 1) {
            var timeout = 100;
            if (!res.data.fromCache) {
              timeout = 100;
            }
            setTimeout(function () {
              self.$set(self.channelList[channelIndex], 'playerLoading', false);
              const chimee = new Chimee({
                wrapper: '#videoPlayer' + channelIndex,
                src: res.data.url,
                controls: true,
                // autoplay: true,
                isLive: true,
                kernels: {
                  hls
                },
                box: 'hls',
              });
              chimee.on('durationchange', function () {
                if (chimee.duration - chimee.currentTime > 10) {
                  chimee.currentTime = chimee.duration - 3;
                }
              });
              chimee.on('canplay', function () {
                chimee.play();
              });
              chimee.on('error', function () {
                //console.log(chimee.error)
              });
              var tryTimes = 0;
              var noLoadTimes = 0;
              var oldDuration = null;
              var interval = setInterval(function () {
                if (oldDuration == chimee.duration) {
                  noLoadTimes++;
                } else {
                  noLoadTimes = 0;
                }
                oldDuration = chimee.duration;
                if (!chimee.duration || noLoadTimes >= 3) {
                  noLoadTimes = 0;
                  chimee.load(res.data.url);
                }
                tryTimes++;
                if (tryTimes > 20) {
                  clearInterval(interval);
                }
              }, 2000);
              self.$set(self.channelList[channelIndex], 'chimee', chimee);
            }, timeout);

          } else {
            self.$set(self.channelList[channelIndex], 'showVideo', false);
            self.$set(self.channelList[channelIndex], 'playerErrorMessage', res.message);
          }
        }
      });
    },
    videoHeatbeat() {
      var self = this;
      setInterval(function () {
        var parkIdCameraSeqs = new Array();
        self.channelList.forEach(element => {
          if (element.videoNum != "x" && element.chimee) {
            parkIdCameraSeqs.push(element.parkId + "," + element.cameraList[element.videoNum - 1].equipmentRecognitionCameraSeq);
          }
        });
        if (parkIdCameraSeqs.length > 0) {
          var params = {
            parkIdCameraSeqs: parkIdCameraSeqs
          };
          $.ajax({
            type: 'get',
            url: '/mgr/monitor/videoHeatbeat.do',
            data: params,
            cache: false,
            dataType: 'json',
            async: true,
            success: function (res) {
              if (res.status == 1) {
                //console.log("videoHeatbeat success");
              }
            }
          });
        }
      }, 60 * 1000 * 3);
    },
    chooseImg(item) {
      item.videoNum = 'x';
      if (item.chimee) {
        item.chimee.destroy();
        item.chimee = null;
      }
    }
  }
}
